<template>
  <el-card v-if="!loading && personData">
    <template #header>
      <div class="card-header">
        <span>{{ personData.personInfo.name }} 的详细信息</span>
        <el-button type="primary" @click="$router.back()">返回</el-button>
      </div>
    </template>

    <!-- 1. 基本信息 -->
    <el-descriptions title="基本信息" :column="2" border>
      <el-descriptions-item label="姓名">{{ personData.personInfo.name }}</el-descriptions-item>
      <el-descriptions-item label="性别">{{ personData.personInfo.gender === 'M' ? '男' : '女' }}</el-descriptions-item>
      <el-descriptions-item label="出生日期">{{ personData.personInfo.birthDate || '未知' }}</el-descriptions-item>
      <el-descriptions-item label="逝世日期">{{ personData.personInfo.deathDate || '未知' }}</el-descriptions-item>
    </el-descriptions>

    <!-- 2. 关系信息 -->
    <el-divider />
    <div class="section-header">
      <h3>关系信息</h3>
      <el-button type="primary" plain @click="openRelationDialog">添加关系</el-button>
    </div>
    <el-table :data="personData.relations" stripe style="width: 100%" empty-text="暂无关系信息">
      <el-table-column prop="relationName" label="关系" width="120" />
      <el-table-column prop="relatedPerson.name" label="姓名" />
      <el-table-column prop="relatedPerson.gender" label="性别">
        <template #default="scope">
          <span v-if="scope.row.relatedPerson">{{ scope.row.relatedPerson.gender === 'M' ? '男' : '女' }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="relatedPerson.birthDate" label="出生日期" />
      <el-table-column label="操作" width="100" fixed="right">
        <template #default="scope">
          <!-- 这个按钮现在可以正常工作了 -->
          <el-button size="small" type="danger" @click="handleDeleteRelation(scope.row.relationId)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 3. 事件信息 -->
    <el-divider />
    <div class="section-header">
      <h3>人生大事</h3>
      <el-button type="primary" plain disabled>添加事件</el-button>
    </div>
    <el-table :data="personData.events" stripe style="width: 100%" empty-text="暂无事件信息">
      <el-table-column prop="eventDate" label="日期" width="180" />
      <el-table-column prop="description" label="事件描述" />
    </el-table>
  </el-card>

  <div v-if="loading" v-loading="loading" element-loading-text="正在加载详情..." style="height: 50vh;"></div>
  <el-empty v-if="!loading && !personData" description="未找到成员信息或ID无效" />

  <RelationshipDialog
      v-if="personData"
      v-model:visible="relationDialogVisible"
      :current-person-id="personData.personInfo.personId"
      :current-person-name="personData.personInfo.name"
      :family-id="personData.personInfo.familyId"
      @success="fetchDetails"
  />
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useRoute } from 'vue-router';
import { getPersonDetailsApi, deleteRelationApi } from '@/api/person';
import type { PersonDetailDTO } from '@/types/api';
import RelationshipDialog from '@/components/RelationshipDialog.vue';
import { ElMessage, ElMessageBox } from 'element-plus';

const route = useRoute();
const loading = ref(true);
const personData = ref<PersonDetailDTO | null>(null);
const relationDialogVisible = ref(false);

const personId = Number(route.params.id);

const fetchDetails = async () => {
  if (personId) {
    loading.value = true;
    try {
      personData.value = await getPersonDetailsApi(personId);
    } catch (error) {
      console.error("获取成员详情失败:", error);
      personData.value = null;
    } finally {
      loading.value = false;
    }
  }
};

const openRelationDialog = () => {
  relationDialogVisible.value = true;
};

/**
 * 处理删除关系的函数
 * @param relationId 要删除的关系的ID
 */
const handleDeleteRelation = async (relationId: number) => {
  try {
    // 弹出确认对话框
    await ElMessageBox.confirm(
      '您确定要删除这条关系吗？此操作不可恢复。',
      '警告',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );
    // 用户点击了“确定删除”
    await deleteRelationApi(relationId);
    ElMessage.success('关系删除成功！');
    // 重新加载详情以刷新列表
    await fetchDetails();
  } catch (error) {
    // 捕获用户点击“取消”或API调用失败的情况
    if (error !== 'cancel') {
      // 如果不是用户主动取消，则打印错误
      console.error("删除关系失败:", error);
    } else {
      ElMessage.info('已取消删除');
    }
  }
};

onMounted(fetchDetails);
</script>

<style scoped>
.card-header, .section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
h3 {
  margin: 0;
  font-size: 18px;
  color: #303133;
}
.el-divider {
  margin: 30px 0;
}
</style>
